package dpyNotepad;
import java.io.*;
import java.util.*;

import javax.microedition.io.Connector;
import javax.microedition.io.file.*;
import javax.microedition.lcdui.*;

public class FolderExplorer extends List {

	private Notepad notepad;
	private String root;
	private Vector filesAndFolders;
	public static final String FOLDER_UP = "../";
	public Image folderImg;
	public Image fileImg;
	
	public FolderExplorer(String title, int type, Notepad notepad) {
		super(title, type);

		this.notepad = notepad;
		this.root = this.notepad.folderPath;
		
		try{
			folderImg = Image.createImage("/folder.png");
			fileImg = Image.createImage("/file.png");
		}
		catch(Exception e){
		}
		
		this.notepad.setTicker(this);
		
		this.setCommandListener(this.notepad);
		this.addCommand(this.notepad.mainMenuCmd);
		this.addCommand(this.notepad.openPadCmd);
		
		if(this.hasRoot()){
			this.append(FOLDER_UP, null);
		}
		
		this.findFilesAndFolders();
		
		for(int i = 0; i < this.filesAndFolders.size(); i++){
			String fileOrFolder = (String)this.filesAndFolders.elementAt(i);
			
			if(fileOrFolder.endsWith("/")){
				this.append(fileOrFolder, this.folderImg);				
			}
			else{
				this.append(fileOrFolder, this.fileImg);		
			}
		}
	}
	
	private boolean hasRoot(){
		return !(this.root == null || this.root == "");
	}
	
	private Vector findFilesAndFolders() {
		
		this.filesAndFolders  = new Vector();
		
		if(!this.hasRoot()){
			try {
		        Enumeration roots = FileSystemRegistry.listRoots();
		        while(roots.hasMoreElements()) {
		            this.filesAndFolders.addElement(roots.nextElement());
		        }
		    } 
			catch(Exception e) {
		    	this.notepad.showAlert("Error in findFilesAndFolders if");
		    }	
		}
		else{
			FileConnection fc = null;
	        try {
	            fc = (FileConnection) Connector.open("file:///" + this.root, Connector.READ_WRITE);
	            Enumeration subFolders = fc.list();
	            while(subFolders.hasMoreElements()) {
		            this.filesAndFolders.addElement(subFolders.nextElement());
		        }

	        } catch (Exception e) {
	            this.notepad.showAlert("Error in findFilesAndFolders else");
	        } finally {
	            try {
	                fc.close();
	            } catch (IOException e) { }
	        }
		}
		
		return this.filesAndFolders;
	}

	public void handleCommand(){	
		int index = this.getSelectedIndex();
		if(index == 0 && this.hasRoot()){
			this.moveFolderUp();
		}
		else{
			String selected = this.getString(index);
			if(selected.endsWith("/")){
				this.moveFolderDown(selected);
			}
			else{
				this.selectFile(selected);
			}
		}
	}
	
	private void moveFolderUp(){
		if(this.notepad.roots.empty()){
			this.notepad.folderPath = "";
		}
		else{
			this.notepad.folderPath = (String)this.notepad.roots.pop();
		}
		//this.notepad.fileName = "";
		this.notepad.goToNewFolderExplorerScreen();
	}
	
	private void moveFolderDown(String folder){
		this.notepad.folderPath += folder;
		//this.notepad.fileName = "";
		this.notepad.roots.addElement(this.notepad.folderPath);
		this.notepad.goToNewFolderExplorerScreen();
	}
	
	private void selectFile(String file){
		this.notepad.fileName = file;
		this.notepad.goToMainMenuExecute();
	}
	
	public static boolean SaveTxtFile(String text, String path, String encoding){
		FileConnection fc = null;
        OutputStream str = null;
		boolean success = true;
		
        try {
            fc = (FileConnection) Connector.open(path, Connector.READ_WRITE);
            if(!fc.exists()) {
                fc.create();
            }
            else{
            	fc.truncate(0);
            }
            
            byte[] bytes = text.getBytes(encoding);
            str = fc.openOutputStream();
            str.write(bytes);            
        } 
        catch (Exception e) { 
        	success = false;
        } 
        finally {
            try {
                fc.close();
            } catch (Exception e) { }
            try {
                str.close();
            } catch (Exception e) { }
        }
        
        return success;
	}
	
	public static String LoadTxtFile(String path, String encoding){
		String result = "";
		
		FileConnection fc = null;
		InputStream str = null;
		ByteArrayOutputStream bos = null;
		try{
			fc= (FileConnection) Connector.open(path, Connector.READ);
			
			str = fc.openInputStream();
			bos = new ByteArrayOutputStream(); 
			int next = str.read();
			while (next > -1) {
			    bos.write(next);
			    next = str.read();
			}

			bos.flush();
			byte[] bytes = bos.toByteArray();
			
			result = new String(bytes, encoding);			
		}
		catch(Exception e){
       		result = "File couldn't load!";			
		}
		finally{
			try{
				bos.close();
			}catch(Exception e){}
			try{
				str.close();
			}catch(Exception e){}
			try{
				fc.close();
			}catch(Exception e){}
		}
		
		return result;
	}
}
